<template>
  <default-home-card icon="SmileOutlined" title="营销统计" :tabs="tabs" @tabChange="onTabChange">
    <div style="height: 300px">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: 215 }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'salesman_name'">
            <div style="display: inline-block; margin-right: 5px">
              <a-image :width="30" :src="record.head_img" />
            </div>
            <span>{{ text }}</span>
          </template>
          <template v-if="column.dataIndex === 'sale_order_num'">
            <div style="color: green"> {{ record.sale_order_amount }} 元 </div>
            <div style="cursor: pointer" @click="toDetail('/sale/sales', { salesman_id: record.id, create_time: time })"> {{ text }} 单 </div>
          </template>
          <template v-if="column.dataIndex === 'return_order_num'">
            <div style="color: coral"> {{ record.return_order_amount }} 元 </div>
            <div style="cursor: pointer" @click="toDetail('/sale/return', { salesman_id: record.id, create_time: time })"> {{ text }} 单 </div>
          </template>
          <template v-if="column.dataIndex === 'visit_num'">
            <div style="cursor: pointer" @click="toDetail('/marketing/visit/records', { salesman_id: record.id, create_time: time })"> {{ text }} 家 </div>
          </template>
          <template v-if="column.dataIndex === 'advance_order_num'">
            <div> {{ record.advance_order_amount }} 元 </div>
            <div> {{ text }} 单 </div>
          </template>
          <template v-if="column.dataIndex === 'period_order_num'">
            <div> {{ record.period_order_amount }} 元 </div>
            <div> {{ text }} 单 </div>
          </template>
          <template v-if="column.dataIndex === 'display_agreement_num'">
            <div style="cursor: pointer" @click="toDetail('/marketing/display/agreement', { salesman_id: record.id, create_time: time })"> {{ text }} 个 </div>
          </template>
        </template>
      </a-table>
      <div class="smart-query-table-page query-table-page">
        <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
      </div>
    </div>
  </default-home-card>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { useQuery } from '@/hooks/web/use-query-hook'
import DefaultHomeCard from '@/views/system/home/components/default-home-card.vue'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { homeApi } from '@/api/system/home-api'

const router = useRouter()
const time_type = ref(1)
const form = ref({
  start_time: '',
  end_time: ''
})
const time = ref([dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')])
const tabs = ref([
  { key: '1', title: '今天' },
  { key: '2', title: '本周' },
  { key: '3', title: '本月' }
])

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '业务员',
    dataIndex: 'salesman_name'
  },
  {
    title: '销售开单',
    dataIndex: 'sale_order_num'
  },
  {
    title: '退货开单',
    dataIndex: 'return_order_num'
  },
  {
    title: '拜访数量',
    dataIndex: 'visit_num'
  },
  {
    title: '预付款订单',
    dataIndex: 'advance_order_num'
  },
  {
    title: '欠款订单',
    dataIndex: 'period_order_num'
  },
  {
    title: '陈列协议',
    dataIndex: 'display_agreement_num'
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData, setQuery } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      time_type: time_type.value
    }
    const res = await homeApi.orderStatistics(data)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {},
  queryFormOp: {}
})
onMounted(queryData)

function onTabChange(key) {
  time_type.value = key
  let [start_time, end_time] = ['', '']
  switch (key) {
    case '1': // 今天
      ;[start_time, end_time] = getTodayRange()
      break
    case '2': // 本周
      ;[start_time, end_time] = getThisWeekRange()
      break
    case '3': // 本月
      ;[start_time, end_time] = getThisMonthRange()
      break
    default:
      ;[start_time, end_time] = getTodayRange() // 默认为今天
  }
  form.value.start_time = dayjs(start_time).format('YYYY-MM-DD')
  form.value.end_time = dayjs(end_time).format('YYYY-MM-DD')
  time.value = [form.value.start_time, form.value.end_time]
  queryData()
}

// 获取今天的时间范围
function getTodayRange() {
  const start = dayjs().startOf('day').toISOString()
  const end = dayjs().endOf('day').toISOString()
  return [start, end]
}

// 获取本周的时间范围
function getThisWeekRange() {
  const start = dayjs().startOf('week').toISOString() // 周一
  const end = dayjs().endOf('week').toISOString() // 周日
  return [start, end]
}

// 获取本月的时间范围
function getThisMonthRange() {
  const start = dayjs().startOf('month').toISOString()
  const end = dayjs().endOf('month').toISOString()
  return [start, end]
}

// 跳转
function toDetail(noticeId, data) {
  router.push({
    path: noticeId,
    query: data
  })
}
</script>

<style lang="less" scoped></style>
